package com.lw.main;

import com.lw.util.Constant;
import com.lw.util.GameUtil;
import lombok.Data;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 小鸟类
 */
@Data
public class Bird {

    private Rectangle rect;//用于碰撞检测

    private boolean life = true;//小鸟生命值，也可以改成数值，表示可以碰撞多少次

    private int acceleration;//小鸟的加速度


    private BufferedImage[] images;//小鸟图片
    public static final int BIRD_IMG_COUNT = 3;

    //小鸟状态
    private int state;

    enum STATE_ENUM {
        STATE_NORMAL, STATE_UP, STATE_DOWN
    }
//    public static final int STATE_NORMAL = 0;//平着飞
//    public static final int STATE_UP = 1;//向上飞
//    public static final int STATE_DOWN = 2;//向下飞

    private boolean up = false, down = false;//小鸟方向
    private int speed = 15;//速度
    private int x = 200, y = 200;//小鸟位置

    public Bird() {
        images = new BufferedImage[BIRD_IMG_COUNT];
        for (int i = 0; i < BIRD_IMG_COUNT; i++) {
            images[i] = GameUtil.loadBufferedImage(Constant.BIRD_IMG[i]);
        }
        int w = images[0].getWidth();
        int h = images[0].getHeight();
        rect = new Rectangle(w,h);
    }

    /**
     * 绘制小鸟
     */
    public void draw(Graphics g) {
        this.flyLogic();
        g.drawImage(images[state], x, y, null);

//        g.drawRect(x,y,rect.width,rect.height);
        rect.x = x;
        rect.y = y;
    }

    /**
     * 控制方向
     */
    public void flyLogic() {
//        if (up) {
//            acceleration--;
//            y+=acceleration;
//            acceleration = Math.max(-10,acceleration);
//            y -= speed;
//            if(y<20) acceleration=0;
//        } else {
//            acceleration++;
//            y+=acceleration;
//            acceleration = Math.min(10,acceleration);
//            y += speed;
//            if(y>Constant.HEIGHT-images[state].getHeight()){
//                acceleration = 0;
//            }
//        }
        if (up) {
            acceleration--;
            y -= speed;
        } else {
            acceleration++;
            y += speed;
        }

        //加速度范围
        y+=acceleration;
        acceleration = GameUtil.rangeNum(acceleration,-10,10);
        if(y==20||y==Constant.HEIGHT-images[state].getHeight()) acceleration=0;

        //控制不飞出边界 20是因为还有标题
        y = GameUtil.rangeNum(y,20,Constant.HEIGHT-images[state].getHeight());
    }

    /**
     * 小鸟移动
     *
     * @param fly
     */
    public void fly(int fly) {
        switch (fly) {
            case 1 -> {
                state = STATE_ENUM.STATE_UP.ordinal();
                up = true;
            }
            case 5 -> {
                state = STATE_ENUM.STATE_DOWN.ordinal();
                up = false;
            }
        }
    }

    /**
     * 重新绘制小鸟位置
     */
    public void restartDraw(){
        this.life = true;
        this.x = 200;
        this.y = 200;
    }
}
